package com.zsj.juc.Atomic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.LongAdder;

/**
 * @author zsj
 * @version 1.0
 * @date 2024/5/17 16:10
 * @description
 */
public class CpuTest {
    public static void main(String[] args) throws InterruptedException {
        //获取cpu的核数 也就是当前系统的cpu的逻辑处理器有多少个
        Runtime runtime = Runtime.getRuntime();
        System.out.println(runtime.availableProcessors());

        CountDownLatch countDownLatch = new CountDownLatch(50);
        Test test = new Test();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 50; i++) {
            new Thread(() -> {
                try {
                    for (int j = 0; j < 1000000; j++) {
                        //test.pp();//严重的性能问题
                        test.adder();
                    }
                } finally {
                    countDownLatch.countDown();
                }
            }, i + "t1").start();
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("消耗时间" + (end - start) + "毫秒");
        System.out.println(test.number);//严重的性能问题
        System.out.println(test.longAdder.sum());
    }
}

class Test {
    private static final Logger log = LoggerFactory.getLogger(Test.class);
    public volatile Integer number = 0;


    //高并发情况下 严重的性能问题
    public synchronized void pp() {
        number++;
    }


    //对以上情况改进 使用LongAdder
    LongAdder longAdder = new LongAdder();

    public void adder() {
        longAdder.increment();
    }
}
